<?php
/**
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

namespace LeoMQ\Realizes\RabbitMQ;


use LeoMQ\Intf\ProducerInterface;
use LeoMQ\MQConsts;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use LeoMQ\Annotations\ProducerRealize;
use Selibra\Tools\Console;
use Swoole\Coroutine;

#[ProducerRealize("rabbitmq")]
class Producer implements ProducerInterface
{

    /**
     * 发布
     * @return mixed
     */
    public function publish($message, $queue, $priority = MQConsts::PRIORITY_LOW)
    {
        $msg = new AMQPMessage($message,
            [
                'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
                'priority' => $priority
            ] # 使消息持久化
        );
        try{
            $amqpConnection = $this->getAMQPConnection();
            $channel = $amqpConnection->channel();
            $result = $channel->basic_publish($msg, '', $queue);
        }catch (\Exception $exception){
            Console::log($exception);
        }

    }


    /**
     * 批量发布
     * @return mixed
     */
    public function batchPublish()
    {
        // TODO: Implement batchPublish() method.
    }


    /**
     * @return AMQPStreamConnection
     */
    private function getAMQPConnection()
    {
        return Connection::getConnectionByC();
    }
}